package com.sunfield.baseframe.base;

import android.content.Context;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangxl on 2016/8/17.
 */
public abstract class MyRecyclerAdapter<T, Holder extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<Holder> {
    protected Context context;
    protected List<T> dataList;

    public MyRecyclerAdapter(Context context) {
        this(context, null);
    }

    public MyRecyclerAdapter(Context context, List<? extends T> dataList) {
        this.context = context;
        this.dataList = new ArrayList<>();
        if(dataList != null) {
            this.dataList.addAll(dataList);
        }
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public T getItem(int position) {
        if(position < 0 || position > dataList.size()){
            return null;
        }
        return dataList.get(position);
    }

    public void updateData(List<? extends T> dataList){
        this.dataList.clear();
        if(dataList != null) {
            this.dataList.addAll(dataList);
        }
        notifyDataSetChanged();
    }

    public void updateData(int position, T data){
        if(position < 0 || position >= dataList.size()){
            return;
        }
        dataList.set(position, data);
        notifyDataSetChanged();
    }

    public void removeData(T data){
        dataList.remove(data);
        notifyDataSetChanged();
    }

    public void removeData(int position){
        if(position < 0 || position >= dataList.size()){
            return;
        }
        dataList.remove(position);
        notifyDataSetChanged();
    }

    public void clear(){
        dataList.clear();
        notifyDataSetChanged();
    }

    public void addData(List<? extends T> dataList){
        if(dataList != null) {
            this.dataList.addAll(dataList);
        }
        notifyDataSetChanged();
    }

    public void addData(T data){
        this.dataList.add(data);
        notifyDataSetChanged();
    }

}
